//express_demo.js 文件
import express from 'express';
import cors from 'cors';
import userRouter from './router/user.js';
import {expressjwt} from 'express-jwt'
import config from './config.js'
import cookieParser from 'cookie-parser';
import cookieSession from 'cookie-session';


var app = express();
app.use(cors());

app.use(express.json()); // for parsing application/json
app.use(express.urlencoded({ extended: false })); // for parsing application/x-www-form-urlencoded

app.use(cookieParser());
app.use(cookieSession({
  name: 'session',
  keys: ['key1'],
  maxAge: 24 * 60 * 60 * 1000 // 24 hours
}))
 
  
app.use(expressjwt({secret:config.JSON_SECRET_KEY,algorithms: ['HS256']}).unless({path:[/^\/api\/login/,/^\/api\/reguser/,/^\/hello/]}))

// 添加错误处理中间件
app.use(function(err, req, res, next) {
  if (err.name === 'UnauthorizedError') {
      return res.status(401).json({
          status: 401,
          message: '请先登录',
          redirect: '/login'  // 前端可以根据这个字段进行跳转
      });
  }
  next(err);
});

app.use("/api",userRouter)
var server = app.listen(8081, function () {
 
app.get('/api/hello', function (req, res) {
   
})
//   var host = server.address().address
//   var port = server.address().port
 
  console.log("应用实例，访问地址为 http://127.0.0.1:8081")
 
})